/** @odoo-module **/

import { patch } from "@web/core/utils/patch";
import { SelectionField } from "@web/views/fields/selection/selection_field";
import mobile from "@web_mobile/js/services/core";

// 状态标签映射
const STATUS_LABELS = {
    'draft': '草稿',
    'reservation': '预订',
    'pending': '待处理',
    'paid': '已支付',
    'discharge': '解除',
    'cancel': '取消'
};

// 扩展选择字段以添加移动端通知
patch(SelectionField.prototype, {
    async onChange(ev) {
        console.log("onChange triggered, field name:", this.props.name);
        
        // 只处理 status 字段
        if (this.props.name === 'status') {
            const oldValue = this.props.record.data[this.props.name];
            const newValue = ev.target.value; // 从事件中获取新值
            console.log("Old status value:", oldValue);
            console.log("New status value from event:", newValue);
            
            // 调用原始的 onChange
            await super.onChange(...arguments);
            
            // 如果值发生了变化
            if (oldValue && newValue && oldValue !== newValue) {
                const newLabel = STATUS_LABELS[newValue] || newValue;
                const message = `状态已改为：${newLabel}`;
                console.log("Showing notification:", message);
                
                // 检查是否在移动应用中
                if (mobile.methods && mobile.methods.showToast) {
                    console.log("Using mobile toast");
                    // 使用移动端 Toast 显示消息
                    try {
                        await mobile.methods.showToast({
                            message: message,
                        });
                        
                        // 震动设备
                        if (mobile.methods.vibrate) {
                            await mobile.methods.vibrate();
                        }
                    } catch (e) {
                        console.log("Mobile methods error:", e);
                    }
                } else {
                    console.log("Using web notification");
                    // 如果不在移动应用中，使用普通通知
                    if (this.env.services && this.env.services.notification) {
                        this.env.services.notification.add(message, {
                            title: '状态更新',
                            type: "success",
                            sticky: false,
                        });
                        console.log("Notification added");
                    } else {
                        console.log("Notification service not found");
                    }
                }
            } else {
                console.log("Status not changed or values are empty", {oldValue, newValue});
            }
        } else {
            // 其他字段直接调用父类方法
            await super.onChange(...arguments);
        }
    }
});

